import Taro, { useReady, createCanvasContext, nextTick } from "@tarojs/taro";
import { View, Canvas, Button } from "@tarojs/components";
import { useRef, useState } from "react";
import "./index.scss";

const SignaturePad = () => {
  const canvasRef = useRef(null);
  const [ctx, setCtx] = useState();
  const points = useRef([]);

  // 初始化 Canvas
  useReady(() => {
    if (!canvasRef.current) return;
    const context = createCanvasContext("signatureCanvas", this);
    setCtx(context);

    // 设置绘制样式
    context.setStrokeStyle("#000000");
    context.setLineWidth(2);
    context.setLineCap("round");
    context.setLineJoin("round");
  });

  // 触摸开始
  const handleStart = (e) => {
    const { x, y } = getEventPosition(e);
    points.current = [{ x, y }];
    ctx?.beginPath();
  };

  // 触摸移动
  const handleMove = (e) => {
    const { x, y } = getEventPosition(e);
    const lastPoint = points.current[points.current.length - 1];
    const midPoint = {
      x: (lastPoint.x + x) / 2,
      y: (lastPoint.y + y) / 2,
    };

    points.current.push(midPoint, { x, y });

    if (points.current.length > 1) {
      ctx?.beginPath();
      ctx?.moveTo(lastPoint.x, lastPoint.y);
      ctx?.quadraticCurveTo(lastPoint.x, lastPoint.y, midPoint.x, midPoint.y);
      ctx?.stroke();
      ctx?.draw(true);
      // 增加二次绘制，确保线条连贯
      ctx?.beginPath();
      ctx?.moveTo(midPoint.x, midPoint.y);
      ctx?.quadraticCurveTo(midPoint.x, midPoint.y, x, y);
      ctx?.stroke();
      ctx?.draw(true);
    }
  };

  // 获取坐标（兼容多平台）
  const getEventPosition = (e) => {
    const touch = e.touches?.[0] || e;
    const rect = canvasRef.current.getBoundingClientRect();
    return {
      x: (touch.x || touch.clientX) - rect.left,
      y: (touch.y || touch.clientY) - rect.top,
    };
  };

  // 清空画布
  const clear = () => {
    ctx?.clearRect(0, 0, 300, 200);
    ctx?.draw();
    points.current = [];
  };

  // 保存签名
  const save = async () => {
    try {
      const res = await Taro.canvasToTempFilePath({
        canvasId: "signatureCanvas",
        fileType: "png",
      });
      Taro.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
      });
    } catch (err) {
      console.error("保存失败:", err);
    }
  };

  return (
    <View className="container">
      <Canvas
        ref={canvasRef}
        canvasId="signatureCanvas"
        id="signatureCanvas"
        disableScroll // 防止滚动干扰
        style={{
          width: "100%",
          height: "200px",
          border: "1px solid #ddd",
          transform: "scale(1)",
          transformOrigin: "0 0",
        }}
        onTouchStart={handleStart}
        onTouchMove={handleMove}
      />

      <View className="buttons">
        <Button className="signature-btn" onClick={clear}>
          清空
        </Button>
        <Button className="signature-btn" onClick={save}>
          保存
        </Button>
      </View>
    </View>
  );
};

export default SignaturePad;
